<template>
  <Dialog v-model="visible" :title="title">
    <!-- <Collapse >
      <CollapseItem name="xxx" title="标题" sub-title="啊啊啊">
        123123
      </CollapseItem>
      <CollapseItem name="aaaa" title="aaaa" sub-title="啊啊啊">
        aaaaa
      </CollapseItem>
    </Collapse> -->
    <Form :model="form" :rules="rules" ref="formRef"  label-width="auto" :column="2">
      <FormItem label="菜单名称" prop="menuName" required :span="0">
        <el-input v-model="form.menuName"/>
      </FormItem>
      <FormItem label="菜单类型" prop="menuType" required :span="0">
          <el-radio-group v-model="form.menuType">
            <el-radio :value="1">目录</el-radio>
            <el-radio :value="2">菜单</el-radio>
          </el-radio-group>
        </FormItem>
      <FormItem label="父级菜单" prop="parentId" :span="0">
        <el-cascader
          v-model="form.parentId"
          :options="menuTree"
          filterable
          clearable
          :props="{ checkStrictly: true, emitPath: false, expandTrigger: 'hover' }"
          placeholder="父级菜单"
          class="w-100%"
        />
      </FormItem>
      <FormItem v-if="form.menuType === 2" label="路径" prop="path" required :span="0">
        <el-input v-model="form.path"/>
      </FormItem>
      <FormItem label="菜单图标" prop="icon" required>
        <el-input v-model="form.icon" :readonly="readonly">
          <template #prepend>
            <Icon v-if="form.icon" :icon="form.icon" />
          </template>
        </el-input>
      </FormItem>
      <FormItem label="显示排序" prop="orderNum" required>
        <el-input-number v-model="form.orderNum" :readonly="readonly" :min="1" controls-position="right"/>
      </FormItem>
      <FormItem label="备注" :span="0">
        <el-input
            v-model="form.remark"
            :readonly="readonly"
            maxlength="200"
            :rows="3"
            placeholder="备注"
            show-word-limit
            type="textarea"
        />
      </FormItem>
  </Form>

    <template #footer v-if="!readonly">
      <el-button @click="visible = false" type="danger">取消</el-button>
      <el-button @click="submit" type="primary">确认</el-button>
    </template>
  </Dialog>
</template>



<script setup lang="ts">

  import {ref, unref, nextTick, watch, reactive, computed} from 'vue'
  import { ElForm,  ElFormItem, ElInput, ElRadioGroup , ElRadio, ElButton, FormRules} from 'element-plus'
  import { Dialog, Form, FormItem, Icon, Collapse, CollapseItem } from "@/components";
  import { listToTree } from '@/utils'
  import { queryDetailApi, selectMenuListApi, saveMenuApi, updateMenuApi } from '@/api/system/menu'
  import type { MenuEditParams } from '@/api/system/menu/types'
  import { MenuRes } from '@/api/system/menu/types'
  const emit = defineEmits<{
    (e: 'submit')
  }>()

  // 菜单数
  const menuTree = ref<MenuRes[]>([])
  const initMenuTree = async () => {
    const res = await selectMenuListApi()
    menuTree.value = listToTree(res.data, {
      valueKey: 'id', 
      labelKey: 'menuName',
      // 过滤只能选菜单 且 可选菜单不能是自己
      filterFn: (item) => item.menuType === 1 && item.id !== menuId.value
    })
  }
  initMenuTree()

  const visible = ref(false)
  const title = computed(() => {
    return readonly.value ? '查看详情' : (menuId.value ? '编辑' : '新增')
  })
  // 是否只读
  const readonly = ref(false)
  const menuId = ref<number>()
  const form = ref<MenuEditParams>()
  const formRef = ref<InstanceType<typeof ElForm>>()
  

  const initData = async () => {
    if (menuId.value) {
      form.value = (await queryDetailApi({ menuId: menuId.value })).data
    } else {
      form.value = {
        id: undefined,        // 菜单ID
        menuName: undefined,  // 菜单名称
        parentId: undefined,  // 父菜单ID
        orderNum: 1,          // 显示顺序
        path: undefined,      // 路由地址
        query: undefined,     // 路由参数
        isCache: undefined,   // 是否缓存（0缓存 1不缓存）
        menuType: undefined,  // 菜单类型（1-目录 2-菜单）
        enableStatus: undefined,    // 启用状态（true启用 false禁用）
        icon: undefined,      // 菜单图标
        remark: undefined,    // 备注
      }
    }
  }
  initData()

  const rules = reactive<FormRules<MenuEditParams>>({
    menuName: [
      { required: true, message: '菜单名称不能为空', trigger: 'blur' },
    ],
    menuType: [
      { required: true, message: '菜单类型不能为空', trigger: 'blur' },
    ],
    path: [
      { required: true, message: '路径不能为空', trigger: 'blur' },
    ],
  })

  watch(
    () => form.value.menuType,
    () => {
      // 目录默认图标
      if (form.value.menuType === 1 && !form.value.icon) {
        form.value.icon = 'ep:menu'
      }
    }
  )


  const submit = async () => {
    await formRef.value.validate(async (valid, fields) => {
      if (valid) {
        const submitParams = { ...form.value, parentId: form.value.parentId ?? 0 }
        if (menuId.value) {
          await updateMenuApi(submitParams)
        } else {
          await saveMenuApi(submitParams)
        }
        emit('submit')
        visible.value = false
      } 
    })
  }

  const openDialog = (id?: number, readonlyFalg = false) => {
    menuId.value = id
    initMenuTree()
    initData()
    readonly.value = readonlyFalg
    visible.value = true
  }



  defineExpose({
    openDialog
  })
</script>
